<template>
  <div class="page-wrap" id="train-table">
    <div class="page-content" :style="{ height: contentHei }">
      <div class="img-header">
        <div style="font-weight: 700;font-size: 18px">任务工程</div>
        <div style="display: flex;justify-content: flex-end;">
          <Input
            v-model.trim="searchTaskName"
            placeholder="名称 / ID"
            clearable
            @on-change="searchTaskNameOreID"
            style="width: 200px;margin-right: 15px;"
          />
          <Button @click="handleLoad"><i class="el-icon-refresh-right"/></Button>
        </div>
      </div>
      <Divider />
      <div class="table-wrap" :style="{ maxHeight: setTableHei }">
        <Table :columns="colData" :data="allData.data"></Table>
        <div style="display: flex;justify-content: center;margin: 15px 0">
          <Page
            :total="trainTotal"
            :page-size="trainPageSize"
            :current="trainPage"
            show-total
            show-elevator
            @on-change="trainOnChange"
          />
        </div>
      </div>
    </div>
    <Modal v-model="relateProModal" width="800" :mask-closable="false" title="相关工程列表">
      <div style="margin-bottom: 15px;display: flex;justify-content: flex-end">
        <Page
          :total="proTotal"
          :page-size="proPageSize"
          show-total
          show-elevator
          placement="top"
          @on-change="userGroupOnChange"
        />
      </div>
      <Table :columns="projectCol" :data="projectList" max-height="600"></Table>
    </Modal>
  </div>
</template>
<script>
import $ from 'jquery';
import cookieUse from '@/libs/cookie.js';
import encryption from '@/libs/encryption.js';
import expandRow from '@/components/table-expand/table-expand.vue';
export default {
  components: {},
  data() {
    return {
      // 用户信息
      proToken: '',
      userID: '',
      isRootDesigner: false,
      companyID: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      setTableHei: 'auto',
      // 菜单背景色
      theme1: 'light',
      initData: [
        {
          style: 2, // 训练样式id
          subject: [{ id: '111', name: '科目1' }], // 训练科目,科目的id列表
          template: [
            //工程模板
            {
              id: 'eb521fa5-a982-4187-84f0-ea02fe4112be',
              name: '测试攻防工具'
            }
          ],
          evaluation: [
            // 采集点id列表
            3005,
            4003,
            3026,
            3007,
            2015,
            3029,
            2009,
            2012,
            2002,
            3025,
            2003,
            3011,
            2010,
            1000,
            4000,
            2016,
            3009,
            4008,
            4001,
            2006,
            2004,
            3008,
            3001,
            2007,
            3018,
            2014,
            2017,
            3027,
            3017,
            2000,
            3022,
            3024,
            1004,
            3014,
            4007,
            2018,
            3028,
            3013,
            3019,
            2005,
            3020,
            3030,
            1002,
            3021,
            3004,
            4006,
            4002,
            4004,
            3006,
            3010,
            2008,
            4011,
            3002,
            1001,
            4010,
            1003,
            2013,
            2001,
            4009,
            3015,
            4005,
            3012,
            3000,
            3003,
            3016,
            2011,
            3023
          ],
          beginning: '2020-01-04 16:00:00', // 训练开始时间
          ending: '2020-01-05 15:59:00', // 训练结束时间
          members: {
            //所有人员
            members_design: [
              //设计人员id列表
              {
                id: '52645f6977b24896a0a9cf2c9a1285ec',
                name: 'htt2_u_auu53'
              },
              {
                id: 'fb6dba7fe021457b8d3fa78ba4cf0044',
                name: 'htt3_u_sjgyi'
              },
              {
                id: '5ce54b1dfd9d4256a2ff45ce3eed3992',
                name: 'bupt_003'
              },
              {
                id: '38fa6ff8f3a0458bbfb390dc48505f31',
                name: 'team1_u_middl'
              },
              {
                id: '2cc196851ee64eda974875018e512dac',
                name: 'team1_u_xasgv'
              }
            ],
            members_evaluate: [] // PG人员id列表
          },
          trial_group: [
            // 人员分组列表
            {
              name: 'test',
              id: '23264cbc420e41b4942f8f034675c053',
              member: [
                { name: 'htt2_u_auu53', id: '52645f6977b24896a0a9cf2c9a1285ec' },
                { name: 'htt3_u_sjgyi', id: 'fb6dba7fe021457b8d3fa78ba4cf0044' },
                { name: 'htt1_u_z890v', id: '8485b6f7e9c94e0fa9f76dd67373b90f' },
                { name: 'team1_u_xasgv', id: '2cc196851ee64eda974875018e512dac' },
                { name: 'team1_u_middl', id: '38fa6ff8f3a0458bbfb390dc48505f31' }
              ]
            }
          ],
          weapons: [
            //攻防工具
            {
              id: '82312336315908096',
              name: 'test'
            }
          ],
          equipments: [
            //实物设备
            {
              id: 'PM655469390a4a30aa8214608121c65c',
              name: 'test'
            }
          ],
          name: 'test202001031736', // 训练名称
          id: 5, // 训练id
          description: 'test202001031736', // 描述
          weapons_type: [],
          flow: [
            //导调
            {
              id: 'd7b55301bd974067bb280a8ea5e6a3f9',
              name: 'vvvv'
            }
          ],
          start_build: '2020-01-03 16:00:00', // 构建开始时间
          end_build: '2020-01-04 15:59:00' // 构建结束时间
        }
      ],
      // allData
      allData: {
        data: []
      },
      colData: [
        {
          type: 'expand',
          width: 40,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '名称',
          key: 'name',
          width: 200,
          tooltip: true
        },
        {
          title: 'ID',
          key: 'id',
          tooltip: true,
          sortable: true,
          sortType: 'desc' // 初始化排序
        },
        {
          title: '创建者',
          key: 'creator',
          // width: 120,
          tooltip: true
        },
        {
          title: '训练模式',
          key: 'style_name',
          tooltip: true
        },
        {
          title: '描述',
          key: 'description',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '训练开始',
          key: 'beginning',
          // width:160,
          tooltip: true
        },
        {
          title: '训练结束',
          key: 'ending',
          // width:160,
          tooltip: true
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h(
                'Dropdown',
                {
                  props: {
                    placement: 'left-start',
                    trigger: 'click'
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'primary'
                      }
                    },
                    [
                      h('span', '操作'),
                      h('Icon', {
                        props: {
                          type: 'ios-arrow-down'
                        },
                        style: {
                          marginLeft: '5px'
                        }
                      })
                    ]
                  ),
                  h(
                    'DropdownMenu',
                    {
                      slot: 'list'
                    },
                    [
                      h('DropdownItem', [
                        h(
                          'Button',
                          {
                            props: {
                              type: 'info'
                            },
                            style: {
                              width: '120px'
                            },
                            on: {
                              click: () => {
                                this.createdProByTrainId(params.row);
                              }
                            }
                          },
                          '创建工程'
                        )
                      ]),
                      h('DropdownItem', [
                        h(
                          'Button',
                          {
                            props: {
                              type: 'info'
                            },
                            style: {
                              width: '120px'
                            },
                            on: {
                              click: () => {
                                this.confirmTask(params.row.id);
                              }
                            }
                          },
                          '确认任务'
                        )
                      ]),
                      h('DropdownItem', [
                        h(
                          'Button',
                          {
                            props: {
                              type: 'info'
                            },
                            style: {
                              width: '120px'
                            },
                            on: {
                              click: () => {
                                this.projectList = [];
                                this.relateProModal = true;
                                this.currentTrainId = params.row.id;
                                this.relatedProject();
                              }
                            }
                          },
                          '相关工程'
                        )
                      ])
                    ]
                  )
                ]
              )
            ]);
          }
        }
      ],
      trainPage: 1,
      trainPageSize: 10,
      trainTotal: 0,
      taskLoading: false,
      // 搜索
      searchTaskName: '',
      // 相关工程
      relateProModal: false,
      projectList: [],
      projectCol: [
        {
          type: 'index',
          width: 60
        },
        {
          title: '工程名称',
          key: 'projectname',
          render: (h, params) => {
            return h(
              'a',
              {
                on: {
                  click: () => {
                    this.goTopo(params.row);
                  }
                }
              },
              params.row.projectname
            );
          }
        },
        {
          title: '训练ID',
          key: 'trainId'
        },
        {
          title: '状态',
          key: 'statusCHName'
        },
        {
          title: '虚拟机数量',
          key: 'vmCount'
        },
        {
          title: '创建者',
          key: 'creatorName'
        },
        {
          title: '描述',
          key: 'description'
        },
        {
          title: '创建时间',
          key: 'createtime'
        }
      ],
      proTotal: 0,
      proPage: 1,
      proPageSize: 10,
      currentTrainId: ''
    };
  },
  created() {
    // 获取用户信息
    this.proToken = cookieUse.getCookie('desig-token');
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.userID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.companyID = November.companyId;
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    let getPage = this.$route.query.page ? this.$route.query.page : 1;
    this.trainPage = getPage;
    this.collectPoint();
    // 获取基本数据
    this.getInfo();
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.contentHei = this.fullHeight - 80 - 60 + 'px'; // 80是头部高度  60是上下padding
      this.setTableHei = this.fullHeight - 80 - 60 - 52 - 49 + 'px';
      this.trainPageSize = Math.floor((this.fullHeight - 305) / 48) - 1;
    },
    // 获取数据
    getInfo() {
      this.allData.data = [];
      this.taskLoading = true;
      let keyWord = '';
      if (this.searchTaskName != '') {
        keyWord = `&keyword=${this.searchTaskName}`;
      }
      // 172.18.2.66     192.168.70.28     /tpi/xgs/  &token=${this.proToken}
      $.ajax({
        async: true,
        url: `/tpi/xgs/trial/trial_config_info?status=103&callback=None&page=${this.trainPage}&perPage=${this.trainPageSize}&token=${this.proToken}&companyId=${this.companyID}${keyWord}`,
        type: 'GET',
        dataType: 'jsonp',
        contentType: 'application/json;charset=utf-8',
        jsonp: 'callback',
        data: {},
        success: (res) => {
          if (res.flag) {
            let getData = res.data;
            this.trainTotal = res.total;
            this.allData.data = getData;
          } else {
            this.$Message.error({
              content: res.message,
              duration: 3
            });
          }
          this.taskLoading = false;
        },
        error: (err) => {
          console.log(err);
          this.taskLoading = false;
        }
      });
    },
    trainOnChange(val) {
      this.trainPage = val;
      this.getInfo();
    },
    searchTaskNameOreID(val) {
      this.searchTaskName = this.searchTaskName;
      this.trainPage = 1;
      this.getInfo();
    },
    // 通过训练id创建工程
    createdProByTrainId(row) {
      this.$router.push({
        name: 'creatProject',
        query: {
          id: row.id,
          temid: row.template ? row.template[0].id : '',
          name: row.template ? row.template[0].name : '',
          action: 'taskProject',
          page: this.trainPage
        }
      });
    },
    // 确认任务
    confirmTask(id) {
      window.openTrain(
        `/tpi/xgs/trial/trialProgress/?id=${id}&sendToken=${this.proToken}&userId=${this.userID}`
      );
    },
    // 查询单个任务
    getSingal(id) {
      $.ajax({
        async: true,
        url: `/tpi/xgs/trial/trial_detail/?id=${id}`,
        type: 'GET',
        dataType: 'jsonp',
        contentType: 'application/json;charset=utf-8',
        jsonp: 'callback',
        data: {},
        success: (res) => {
          let getMembers = res.members ? res.members : [];
          if (this.isRootDesigner) {
            this.allData.data.push(res);
          } else {
            for (let j = 0; j < getMembers.length; j++) {
              if (
                this.userID === getMembers[j].id &&
                getMembers[j].type === 'designer' &&
                getMembers[j].role != 'evaluator'
              ) {
                this.allData.data.push(res);
                return;
              }
            }
          }
        },
        error: (err) => {
          console.log(err);
        }
      });
    },
    // 查看相关工程
    relatedProject() {
      // 是否是单位管理员
      let enableAll = '';
      let creator = '';
      if (this.isRootDesigner) {
        enableAll = `&enableAll=true`;
      } else {
        // enableAll = `&enableAll=${this.enableAll}`
        creator = `&creator=${this.userID}`;
      }
      this.axios
        .get(
          `${this.baseURL}/topo-edit/projects/list?page=${this.proPage}&pageSize=${this.proPageSize}&order=desc${creator}&trainId=${this.currentTrainId}${enableAll}`
        )
        .then((res) => {
          if (res.data.code === 1) {
            let attribute = res.data.attribute;
            this.projectList = attribute.dataList;
            this.proTotal = attribute.totalCount;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    userGroupOnChange(val) {
      this.proPage = val;
      this.relatedProject();
    },
    // 跳转topo页面
    goTopo(item) {
      let stateText = item.statusCHName;
      if (stateText === '工程导入中') {
        this.$Message.info({
          content: '该工程正在导入中...',
          duration: 3
        });
        return false;
      } else if (stateText === '删除中') {
        this.$Message.info({
          content: '该工程正在删除中...',
          duration: 3
        });
        return false;
      } else if (stateText === '工程导入失败') {
        this.$Message.info({
          content: '该工程导入失败！',
          duration: 3
        });
        return false;
      }
      window.openTrain(`/topologyProject/index.html#/topologyDisplay/topologys?projectId=${item.id}`);
    },
    // 刷新
    handleLoad() {
      // this.trainPage = 1
      this.searchTaskName = '';
      this.getInfo();
    },
    // 采集点数据
    collectPoint() {
      // 采集点id列表
      $.ajax({
        async: true,
        url: '/tpi/butp/index/all/detail',
        type: 'GET',
        contentType: 'application/json;charset=utf-8',
        data: {},
        success: (res) => {
          if (res.flag) {
            let json = res.data;
            // 数据源
            let NODES = json.nodes;
            let EDGES = json.edges;
            // 整理数据
            let Arrangement = {};
            for (let i = 0; i < NODES.length; i++) {
              Arrangement[NODES[i].id] = NODES[i];
            }
            localStorage.setItem('desi-coll-point', JSON.stringify(Arrangement));
          } else {
            this.$Message.error({
              content: '数据获取失败！',
              duration: 3
            });
          }
        },
        error: (err) => {
          console.log(err);
        }
      });
    }
  }
};
</script>
<style scoped>
.page-wrap {
  padding: 30px;
}
.page-content {
  background-color: #fff;
  border-radius: 10px;
}
.img-header {
  display: flex;
  justify-content: space-between;
  padding: 20px 30px 0 30px;
}
.table-wrap {
  padding: 0 30px;
  overflow-x: hidden;
  overflow-y: auto;
}
.table-wrap::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 6px;
}
.table-wrap::-webkit-scrollbar-thumb {
  /*滚动条里面小方块样式*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(209, 209, 209, 0.6);
}
.table-wrap::-webkit-scrollbar-track {
  /*滚动条里面轨道样式*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  background: rgba(179, 179, 179, 0.1);
}
</style>
<style>
#train-table .ivu-table-wrapper {
  margin-top: 1px;
  position: inherit !important;
}
#train-table .ivu-select-dropdown {
  z-index: 9999;
}
</style>
